import { ref, toRefs } from 'vue'

import { fileTreeAtom } from '@renderer/store/jotai'
import { getFileIdOrNameFromLink } from '@renderer/utils/file'
import { useAtom } from 'jotai-vue'
import useCurrentFile from '@renderer/hooks/useCurrentFile'
import useTabJsonModel from '@renderer/hooks/useTabJsonModel'

export default function useDoubleLink(outerJump) {
  const fileTree = useAtom(fileTreeAtom)[0]
  const { updateCurrentFile } = useCurrentFile()
  const { model: tabModel, updateTabJsonModelWhenCurrentFileChanged } = useTabJsonModel()

  const onLinkOpen = async (elementOrLink, event) => {
    if (event) {
      event.preventDefault()
    }

    const link = typeof elementOrLink === 'string' ? elementOrLink : elementOrLink.link
    const fileIdOrNameInRevezone = link && getFileIdOrNameFromLink(link)

    if (fileIdOrNameInRevezone) {
      let file = fileTree[fileIdOrNameInRevezone]?.data

      if (!file) {
        file = Object.values(fileTree).find(
          (item) => item.data.name === fileIdOrNameInRevezone
        )?.data
      }

      if (file) {
        await updateCurrentFile(file)
        updateTabJsonModelWhenCurrentFileChanged(file, tabModel)
      }
    } else {
      if (outerJump) {
        link && window.open(link)
      }
    }
  }

  return { onLinkOpen, tabModel, fileTree }
}
